package pers.chao.tool.infrastructure.format;

import pers.chao.tool.infrastructure.ParameterFormatUtil;

/**
 * Description: 文案格式化
 *
 * @author W.Chao
 * @date 2020/10/10 0:03
 **/
public final class TextTemplateUtil {
	private TextTemplateUtil() {
	}

	/**
	 * 文案格式化，使用{}作为占位符
	 * 保留{}时的写法：{{}}
	 *
	 * @param format
	 * @param args
	 * @return
	 */
	public static String format(String format, Object... args) {
		final int len = Math.max(1, format == null ? 0 : format.length() >> 1);
		int[] indices = new int[len];
		final int placeholders = ParameterFormatUtil.countArgumentPlaceholders2(format, indices);
		int usedCount = Math.min(placeholders, args == null ? 0 : args.length); // userCount表示实际args参数个数
		return formatMessage(indices, usedCount, format, args);
	}

	private static String formatMessage(int[] indices, int usedCount, String format, Object... args) {
		StringBuilder stringBuilder = new StringBuilder();
		if (indices[0] < 0) {
			// indices[0]<0表示format中存在转义字符
			ParameterFormatUtil.formatMessage(stringBuilder, format, args, usedCount);
		} else {
			ParameterFormatUtil.formatMessage2(stringBuilder, format, args, usedCount, indices);
		}
		return stringBuilder.toString();
	}
}
